﻿using CardMonitor.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using DotNetSpeech;
using CardMonitor.Pages;
using CardMonitor.Windows;
using CardMonitor.Model;
using Newtonsoft.Json.Linq;

namespace CardMonitor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DispatcherTimer timer;
        private String TextProperty1 = String.Empty;
        SpVoice speech = new SpVoice();
        MainWindow mainWindow;
        IntPtr icdev = IntPtr.Zero;

        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timeCycle);
            timer.Start();

            mainWindow = this;

            this.Loaded += Window_Load;
            this.Unloaded += Window_UnLoad;
 
        }
        private void Window_Load(object sender, EventArgs e)
        {

           int code= NewIDcardread.Opendevice();//打开读卡设备
            if (code != 1) {

                MessageBox.Show("打开设备失败" );

            }
                
            /*    string sMsg = string.Empty;//打开读卡设备神思
                if ("1".Equals(App.getConfig().IDCardDevice)) {
                    if (!IDCardReader.InitCom(0, out sMsg))
                    {
                        MessageBox.Show(sMsg);
                    }
                    //int handle = CommonInterface.OpenDevice(CommonInterface.PortType, CommonInterface.PortPara, CommonInterface.ExtendPara);
                    //if (handle <= 0)
                    //{
                    //    MessageBox.Show("打开设备失败，错误代码：" + handle.ToString());
                    //    return;
                    //}
                }*/

            PortControlHelper cardCom = App.getGlobalVariables().cardComm;//吐卡器
            if (null == cardCom)
            {
                App.getGlobalVariables().cardComm = new PortControlHelper();
            }
    /*        if (!App.getGlobalVariables().cardComm.PortState)
            {
                icdev = Reader.hc_init(6, 115200);
                if (icdev.ToInt32() > 0)
                {
                    StringBuilder ver = new StringBuilder(32);
                    Reader.srd_ver(icdev, 0, ver);
                    Reader.dv_beep(icdev, 30);
                    MessageBox.Show(ver.ToString(0, 32));
                }
                else
                {
                    MessageBox.Show("Connect Reader falied.");
                }
            }*/

            PortControlHelper cardDeviceComm = App.getGlobalVariables().cardDeviceComm;
            if (null == cardDeviceComm)
            {
                App.getGlobalVariables().cardDeviceComm = new PortControlHelper();
            }
            if (!App.getGlobalVariables().cardDeviceComm.PortState)
            {
                App.getGlobalVariables().cardDeviceComm.OpenPort(App.getConfig().Card_Device_PortName, 9600, 8, 1);
            }

            Index indexPage = new Index(this);
            //indexPage.getIcPtr(icdev);
            frmMain.Content = indexPage;
        }
        private void Window_UnLoad(object sender, EventArgs e)
        {
            string sMsg = string.Empty;
            if ("1".Equals(App.getConfig().IDCardDevice))
            {
                try
                {
                    IDCardReader.CloseCom(0, out sMsg);
                    //int Handle = CommonInterface.GetCurrentDevice();

                    //int ret = CommonInterface.CloseDevice();
                    //if (ret != 0)
                    //{
                    //    return;
                    //}
                }
                catch { }
            }
            try
            {
                if (App.getGlobalVariables().cardDeviceComm.PortState)
                {
                    App.getGlobalVariables().cardDeviceComm.ClosePort();
                }
                //if (App.getGlobalVariables().cardComm.PortState)
                //{
                //    //App.getGlobalVariables().cardComm.ClosePort();
                //    Reader.hc_exit(icdev);
                //}
            }
            catch { }
        }
        public void timeCycle(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                Application.Current.Dispatcher.BeginInvoke(
                    new Action(() =>
                    {
                        TextProperty1 = DateTime.Now.ToString();
                        this.labelTime.Content = TextProperty1;
                    }));
            }).Start();
        }

        public void Speak(String message)
        {
            speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
        public void BreakSpeak()
        {
            speech.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
        }

        private void imgLogo_MouseUp(object sender, MouseButtonEventArgs e)//logo点击事件
        {
            PasswordWindow passwordWindow = new PasswordWindow();
            passwordWindow.Owner = mainWindow;
            bool result = (bool)passwordWindow.ShowDialog();
            if (!result)
            {
                return;
            }

            SettingWindow win = new SettingWindow();
            win.Owner = mainWindow;
            result = (bool)win.ShowDialog();
            if (result)
            {
                Application.Current.Shutdown();
            }
        }

        private void frmMain_Navigated(object sender, NavigationEventArgs e)
        {

        }
        private int checkCard(JObject paramObj)
        {
            ReadCardWindow readcardWindow = new ReadCardWindow();

            bool result = (bool)readcardWindow.ShowDialog();
            if (!result)
            {
                return -1;
            }
            String guidCode = paramObj["guidCode"].ToString();
            if (!guidCode.Equals(readcardWindow.billModel.FacId))
            {
                return -2;
            }
            String carNum = paramObj["carNumber"].ToString();
            if (!carNum.Equals(readcardWindow.billModel.CarNumber))
            {
                return -3;
            }
            String control = paramObj["control"].ToString();
            if (!control.Equals(readcardWindow.billModel.ProdCode))
            {
                return -4;
            }
            String billCode = paramObj["billCode"].ToString();
            if (!billCode.Equals(readcardWindow.billModel.Code))
            {
                return -5;
            }
            String ynum = paramObj["ynum"].ToString();
            if (!ynum.Equals(readcardWindow.planNum))
            {
                return -6;
            }

            return 1;
        }
        private void ceshi(object sender, RoutedEventArgs e)
        {
            /*  PortControlHelper portControlHelper = new PortControlHelper();
              portControlHelper.WriteICCardData("COM8", 0x01,"370523200103272415");*/
            BillModel billModel = new BillModel();
            billModel.Juid = "370523200103272415";
            MakeCardWindow makeCardWindow = new MakeCardWindow();
            makeCardWindow.setModel(billModel);
            //makeCardWindow.Show();
            makeCardWindow.Owner = mainWindow;// 建立窗口层级关系
            bool result = (bool)makeCardWindow.ShowDialog();//显示窗口
            if (result)
            {
                JObject json = new JObject();
                json.Add("guidCode", billModel.Juid);
                //json.Add("control", billModel.Control);
                //json.Add("billCode", billModel.BillNo.Substring(billModel.BillNo.Length - 8));
                json.Add("carNumber", billModel.CarNumber);
                int checkResult = this.checkCard(json);//写卡
                if (checkResult != 1)
                {
                   // showMessage("写卡校验失败,请重新点击制卡");
                    NavigationService.GetNavigationService(this).GoBack();
                    CardDeviceUtil.ReceiveCard();//回收卡
                    return;
                }

                HttpPostWindow httpPostWindow = new HttpPostWindow();
                httpPostWindow.Owner = mainWindow;

                JObject paramJSON = new JObject();
                paramJSON.Add("id", billModel.Id);
                paramJSON.Add("guid", billModel.Juid);
                // paramJSON.Add("WaiPiWeight()", getZhong("waiPi").ToString("0.00"));
                // paramJSON.Add("waiMaoWeight", getZhong("waiMao").ToString("0.00"));

                httpPostWindow.setParamObject(paramJSON);

                httpPostWindow.setOperation(HttpPostWindow.OperationType.uploadMakeCardResult.ToString());
                result = (bool)httpPostWindow.ShowDialog();
                if (!result)
                {
                    string message = httpPostWindow.getMessage();
                    if (null == message || "".Equals(message))
                    {
                        message = "制卡失败,请联系管理员";
                    }
                    mainWindow.Speak("制卡失败，请联系客服人工处理");
                  //  showMessage(message);
                    CardDeviceUtil.ReceiveCard();
                    NavigationService.GetNavigationService(this).GoBack();

                    return;
                }



                mainWindow.Speak("制卡成功");
                // MakeCardSucces();////弹卡
                CardDeviceUtil.PopupCard(); ;////弹卡


            }
        }
    }
}
